<template>
  <div class="tabs">
    <div class="tabs-header">
      <span
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ 'tab-active': activeTab === index }"
        @click="activateTab(index)"
        class="tab-button"
      >
        {{ tab.title }}
      </span>
    </div>
    <div class="tabs-content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Tabs',
  props: {
    value: {
      type: [String, Number],
      default: 0,
    },
  },
  data() {
    return {
      tabs: [],
      activeTab: this.value,
    };
  },
  watch: {
    value(newVal) {
      this.activeTab = newVal;
    },
  },

  provide() {
    return {
      tabs: {
        register: this.registerTab,
        unregister: this.unregisterTab,
        activeTab: () => this.activeTab,
      },
    };
  },
  methods: {
    activateTab(index) {
      console.log(
        '%c [ index ]-52',
        'font-size:13px; background:pink; color:#bf2c9f;',
        index
      );
      this.activeTab = index;
      this.$emit('input', index);
      this.$emit('change', index);
    },
    registerTab(tab) {
      this.tabs.push(tab);
    },
    unregisterTab(tab) {
      const index = this.tabs.findIndex((t) => t === tab);
      if (index !== -1) {
        this.tabs.splice(index, 1);
        // 如果删除的是当前激活的标签页，激活第一个标签页
        if (this.activeTab >= this.tabs.length) {
          this.activeTab = Math.max(0, this.tabs.length - 1);
          this.$emit('input', this.activeTab);
        }
      }
    },
  },
};
</script>

<style scoped>
.tabs {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.tabs-header {
  display: flex;
  border-bottom: 1px solid var(--color-border-default, #38414a);
}

.tab-button {
  flex: 1;
  text-align: center;
  line-height: 32px;
  color: #fff;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-active {
  color: #fff;
  background-color: var(--color-background-brand-default, #1d7afc);
}

.tabs-content {
  flex: 1;
  flex-basis: auto;
}
</style>
